<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";

//tag-search
const value = ref("");
const onSearch = (val) => {
  const jsonStr = JSON.stringify(originTagList);
  tagList.value = JSON.parse(jsonStr);
  tagList.value.forEach((parentTag) => {
    parentTag.children = parentTag.children.filter((tag) => {
      return tag.text.includes(val);
    });
  });
};
const onCancel = () => {
  tagList.value = originTagList;
};
//treeSelect
const originTagList = [
  {
    text: "性别",
    children: [
      {
        text: "男",
        id: 1,
      },
      {
        text: "女",
        id: 2,
      },
    ],
  },
  {
    text: "年级",
    children: [
      {
        text: "大一",
        id: 3,
      },
      {
        text: "大二",
        id: 4,
      },
      {
        text: "大三",
        id: 5,
      },
      {
        text: "大四",
        id: 6,
      },
    ],
  },
];
let tagList = ref(originTagList);
//扁平化处理
const id_tags = originTagList.flatMap((item) => [...item.children]);
let activeId = ref([]);
const activeIndex = ref(0);
//tag
const close = (id) => {
  activeId.value = activeId.value.filter((item) => item != id);
};
//user search
const router = useRouter();
const doSearch = () => {
  let tagNameList: any = [];
  activeId.value.forEach((id) => {
    tagNameList.push(id_tags[id - 1].text);
  });
  router.push({
    path: "/user/list",
    query: { tagNameList },
  });
};
</script>

<template>
  <form action="/">
    <van-search
      v-model="value"
      show-action
      placeholder="请输入标签"
      @search="onSearch"
      @cancel="onCancel"
    />
  </form>
  <van-divider content-position="left">已选标签</van-divider>
  <div v-if="activeId.length === 0">请选择标签</div>
  <van-row>
    <van-col span="4" v-for="id in activeId" :key="id" offset="1">
      <van-tag closeable size="small" type="primary" @close="close(id)">
        {{ id_tags[id - 1].text }}
      </van-tag>
    </van-col>
  </van-row>
  <van-divider content-position="left">选择标签</van-divider>
  <van-tree-select
    v-model:active-id="activeId"
    v-model:main-active-index="activeIndex"
    :items="tagList"
    height="200"
  />
  <div style="padding: 20px 40px">
    <van-button
      type="primary"
      size="small"
      style="width: 100%"
      @click="doSearch"
      >搜索
    </van-button>
  </div>
</template>

<style scoped></style>
